<script setup lang="ts">
import { useECharts } from '@vc/use';
import { type EChartsOption } from 'echarts';
import { type Ref } from 'vue';

interface Props {
  /** 是否显示 */
  show?: boolean;
  /** 名称 */
  currentName?: string;
  /** 弹窗数据 */
  detail: any;
}

const { show = true, currentName, detail } = defineProps<Props>();

const chartRef = ref<HTMLDivElement | null>(null);

const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);

let barOption = {
  title: {
    left: '3%',
    top: '-3%',
    textStyle: {
      width: 50,
      height: 12,
      fontSize: 10,
      fontFamily: 'PingFangSC-Light',
      fontWeight: 300,
      textAlign: 'left',
      color: '#3c3c3c',
      lineHeight: 21
    }
  },
  tooltip: {
    trigger: 'axis',
    confine: true,
    backgroundColor: 'rgba(255, 255, 255, 0.8)', // 设置背景颜色
    textStyle: {
      color: '#3C3C3C', // 设置文字颜色
      fontSize: 10
    },
    extraCssText: 'z-index:10',
    formatter: function (params) {
      let astr = '';
      params.forEach((ele) => {
        // 不为0的展示
        astr += `<div style="height:15px;font-size:6px">
                      <i style="width: 7px;height: 7px;display: inline-block;background: ${ele.color};"></i>
                      <span>${ele.seriesName}: ${ele.data}</span>
                    </div>`;
      });
      const b = '<div>' + `<p style="margin: 0;">${params[0].axisValue}</p>` + astr + '<div>';
      return b;
    }
  },
  legend: {
    data: ['温室气体排放（吨CO2e）', '同比变化（%）'],
    bottom: 0,
    itemWidth: 8,
    itemHeight: 8,
    fontSize: 12
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '20%',
    top: '13%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      data: '',
      axisLabel: {
        width: 50,
        color: '#8c8c8c',
        fontSize: 10
      },
      axisTick: {
        alignWithLabel: true
      },
      axisLine: {
        lineStyle: {
          color: '#e1e1e1'
        }
      },
      splitLine: {
        show: false,
        lineStyle: {
          type: 'solid',
          color: '#eee'
        }
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      name: '单位（万元）',
      splitLine: {
        show: false,
        lineStyle: {
          type: 'solid',
          color: '#eee'
        }
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#e1e1e1'
        }
      },
      axisTick: {
        color: '#b7b7b7'
      },
      axisLabel: {
        color: '#8c8c8c',
        fontSize: 10
      },
      nameTextStyle: {
        color: '#8c8c8c',
        fontSize: 10
      }
    },
    {
      type: 'value',
      name: '%',
      splitLine: {
        show: false,
        lineStyle: {
          type: 'solid',
          color: '#eee'
        }
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#e1e1e1'
        }
      },
      axisTick: {
        color: '#b7b7b7'
      },
      axisLabel: {
        color: '#8c8c8c',
        fontSize: 10
      },
      nameTextStyle: {
        color: '#8c8c8c',
        fontSize: 10
      }
    }
  ],
  color: ['#2D99FF', '#FF6C40'],
  series: [
    {
      name: '同比变化',
      type: 'line',
      data: '',
      symbolSize: 10,
      /* itemStyle: {
       color: '#ffcda3',
       borderColor: '#ff7500',
       },*/
      yAxisIndex: 1,
      lineStyle: {
        color: '#2D99FF',
        width: 1
      }
    },
    {
      name: '温室气体排放',
      type: 'bar',
      barWidth: '10',
      itemStyle: {
        color: 'red',
        normal: {
          // 这里设置柱形图圆角 [左上角，右上角，右下角，左下角]
          barBorderRadius: [10, 10, 0, 0]
        }
      },
      data: ''
    }
  ]
};

function setValueShow(value) {
  let val = value && value.replace(/,/g, '').split('.')[0];
  if (val >= 1000000 && val <= 1000000000) {
    return (val / 10000).toFixed(2);
  } else if (val > 1000000000) {
    return (val / 100000000).toFixed(2);
  } else {
    return value;
  }
}

function getUnit(val) {
  if (val >= 1000000 && val <= 1000000000) {
    return '万';
  } else if (val > 1000000000) {
    return '亿';
  } else {
    return '';
  }
}

function renderChart(data) {
  let keyArr = ['yoy', 'value'];
  let xAxisArr = [];
  xAxisArr = data.map((item) => item.year);
  barOption.xAxis[0].data = xAxisArr as any;
  let seriesData: { value: Numberish[]; yoy: Numberish[] } = { value: [], yoy: [] };
  let getMaxValue: Numberish[] = [];
  data.forEach((item) => {
    seriesData.value.push(setValueShow(item.value && item.value.replaceAll(/,/g, '')));
    seriesData.yoy.push(item.yoy ? item.yoy.split('%')[0] : '-');
    getMaxValue.push(item.value && item.value.replaceAll(/,/g, ''));
  });
  // 获取最大值，方便单位处理
  let maxValue = getMaxValue.sort().reverse()[0];
  barOption.series.map((item, index) => {
    item.data = seriesData[keyArr[index]];
  });
  // 设置图例+单位
  barOption.legend.data = [detail.name, '同比变化'];
  barOption.series[1].name = detail.name;
  barOption.yAxis[0].name = getUnit(maxValue) + data[0].indicatorDisplayUnit;
  setOptions(barOption as EChartsOption);
}

const emit = defineEmits(['update:show','close']);

const modelValue = computed({
  get() {
    return show;
  },
  set(value) {
    emit('update:show', value);
  }
});

const handleClose = () => {
  modelValue.value = false;
  emit('close');
  emit('update:show', false);
};

onMounted(() => {
  nextTick(() => {
    renderChart(detail.values.slice().reverse());
  });
});

</script>

<template>
  <vc-dialog v-if="show" v-model="modelValue" :title="currentName" width="500" @close="handleClose">
    <div class="wrapper" @click.stop>
      <div class="chart" ref="chartRef" style="height: 220px" />
      <div class="table">
        <table>
          <tr>
            <th style="width: 150px; text-align: center">年度</th>
            <th style="width: calc(100% - 250px)">{{ detail.name }}（{{ detail.unit }}）</th>
            <th style="width: 100px">同比变化(%)</th>
          </tr>
          <tr v-for="(item, index) in detail.values" :key="index">
            <td style="width: 150px; text-align: center">{{ item.year }}</td>
            <td style="width: calc(100% - 250px)">{{ item.value }}</td>
            <td style="width: 100px">
              {{ item.yoy ? item.yoy.split('%')[0] : '--' }}
            </td>
          </tr>
        </table>
      </div>
    </div>
  </vc-dialog>
</template>

<style lang="scss" scoped>
.wrapper {
  padding: 15px 10px;
  overflow: auto;

  .titleFirst {
    font-weight: bold;
    font-size: 13px;
    line-height: 22px;
    color: #000000;
    position: relative;
    padding-left: 18px;
    position: relative;
    margin-top: 15px;

    &::before {
      content: '';
      position: absolute;
      width: 4px;
      height: 2px;
      left: 0;
      top: 3px;
      background: #15b4f1;
    }
  }

  .table {
    padding: 10px;

    table {
      width: 100%;

      tr {
        width: 100%;
        display: flex;
        justify-content: space-between;

        th {
          color: #8b8c8c;
          font-size: 13px;
          font-weight: normal;
          line-height: 22px;
          text-align: right;
        }

        td {
          font-size: 13px;
          line-height: 22px;
          text-align: right;
        }
      }
    }
  }
}
</style>
